package com.zhongxi.guoyuan.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Environment;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/11/29.
 */

public class CommonTool {

    private static final double EARTH_RADIUS = 6378137.0;

    /**
     * //     * @param id
     *
     * @return 设置imageloader的默认图片
     *//*
    public static DisplayImageOptions getOptions(int id) {

        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(id)
                .showImageForEmptyUri(id)
                .showImageOnFail(id)
                .cacheInMemory(false).bitmapConfig(Bitmap.Config.RGB_565)
                .cacheOnDisk(false)
                .displayer(new RoundedBitmapDisplayer(20))
                .build();
        return options;
    }*/

    // 返回单位是千米
    public static String getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return DataUtil.divide(String.valueOf(Math.round(s * 10000)), "10000000", 2) + "Km";
    }

    public static String getDistanceKM(double longitude1, double latitude1,
                                       double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return DataUtil.divide(String.valueOf(Math.round(s * 10000)), "10000000", 2);
    }

    // 返回单位是米
    public static String getDistanceOfM(double longitude1, double latitude1,
                                        double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return DataUtil.divide(String.valueOf(Math.round(s * 10000)), "10000", 0);
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * dip转为 px
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 从 px(像素) 的单位 转成为 dp
     */
    public static float px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return pxValue / scale + 0.5f;
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param context （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param context （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 将String型格式化,比如想要将2011-11-11格式化成2011年11月11日,就StringPattern("2011-11-11","yyyy-MM-dd","yyyy年MM月dd日").
     *
     * @param date       String 想要格式化的日期
     * @param oldPattern String 想要格式化的日期的现有格式
     * @param newPattern String 想要格式化成什么格式
     * @return String
     */
    public static String StringPattern(String date, String oldPattern, String newPattern) {
        if (date == null || oldPattern == null || newPattern == null)
            return "";
        SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern);        // 实例化模板对象
        SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern);        // 实例化模板对象
        Date d = null;
        try {
            d = sdf1.parse(date);   // 将给定的字符串中的日期提取出来
        } catch (Exception e) {            // 如果提供的字符串格式有错误，则进行异常处理
            e.printStackTrace();       // 打印异常信息
        }
        return sdf2.format(d);
    }

    public static Boolean TimeCompare(String stime, String etime) {
        try {
            //格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date beginTime = sdf.parse(stime);
            Date endTime = sdf.parse(etime);
            //判断时间大小
            if ((endTime.getTime() - beginTime.getTime() >= 0)) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
     * 将手机号格式化，中间4位隐藏
	 */
    public static String formatPhone(String dataMobile) {
        String dataPhone = "";
        try {
            dataPhone = dataMobile.substring(0, 3) + "****"
                    + dataMobile.substring(7, 11);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataPhone;
    }

    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength() / 1024 / 1024);   //改成MB的
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                pd.setProgress(total / 1024 / 1024);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 提供精确的减法运算。
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static boolean sub(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.subtract(b2).doubleValue() >= 0 ? true : false;
    }

    public static boolean sub2(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.subtract(b2).doubleValue() > 0 ? true : false;
    }

    public static String formatYesterday() {
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.DATE, -1);
        return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    }

    public static String todayYesterday() {
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.DATE, 0);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(cal.getTime());
    }

    public static String formatDate(String time) {

        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            calendar.setTime(sdf.parse(time));

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdf.format(calendar.getTime());
    }

    /**
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]+.*[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 隐藏软键盘
     *
     * @param view    接受软键盘输入的视图，一般为edittextview
     * @param context
     */
    public static void hideSoft(View view, Context context) {
        InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null) {
            im.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     *
     * @param view
     * @param context
     */
    public static void showSoft(View view, Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }


//    private boolean isSoftShowing(Context context) {
//        //获取当前屏幕内容的高度
//        int screenHeight =getWindow().getDecorView().getHeight();
//        //获取View可见区域的bottom
//        Rect rect = new Rect();
//        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
//
//        return screenHeight - rect.bottom != 0;
//    }


    /**
     * 小数取整
     *
     * @param str
     * @return
     */
    public static String getWhole(String str) {
        if (str.contains(".")) {
            int i = str.indexOf(".");
            return str.substring(0, i);
        }
        return str;
    }

    static long lastTime = 0;
    private static final long SINTTIME = 1000;

    public static boolean isFirstScroll() {
        long mCurrentTime = System.currentTimeMillis();
        boolean flag = false;
        if (mCurrentTime - lastTime >= SINTTIME) {
            lastTime = mCurrentTime;
            flag = true;
        }
        return flag;
    }

    private static final long SINTTIMELONG = 5000;

    public static boolean isFirstLongScroll() {
        long mCurrentTime = System.currentTimeMillis();
        boolean flag = false;
        if (mCurrentTime - lastTime >= SINTTIMELONG) {
            lastTime = mCurrentTime;
            flag = true;
        }
        return flag;
    }

    /***
     * 检查qq app是否安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName
                    , PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

    }

    /***
     * 检测是否安装微信客户端
     */
    private static IWXAPI api;

    public static boolean checkWxExist(Context context) {

        api = WXAPIFactory.createWXAPI(context, Constants.APP_ID);
        if (api.isWXAppInstalled() && api.isWXAppSupportAPI()) {
            return true;
        } else {
            PackageManager manager = context.getPackageManager();
            List<PackageInfo> infoList = manager.getInstalledPackages(0);
            if (infoList != null) {
                for (int i = 0; i < infoList.size(); i++) {
                    String name = infoList.get(i).packageName;
                    if (name.equals("com.tencent.mm")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }

        return false;
    }
}